<?php
/**
 * 支付宝管理
 *
 * @author        chenfenghua <843958575@qq.com>
 * @copyright     Copyright (c) 2011-2015 shop. All rights reserved.
 * @link          http://www.yiitian.com
 * @package       /protected/modules/b2c/controllers
 * @version       v1.0.0
 */

class AlipayController extends B2cController
{

    public function actionPc()
    {
        header("Content-type:text/html;charset=utf-8");
        $alipay_config = array();
        include(Yii::app()->basePath.'/extensions/alipay_direct/alipay.config.php');
        include(Yii::app()->basePath.'/extensions/alipay_direct/lib/alipay_submit.class.php');

        $modelConfig = new ModelConfig();
        $alipay_arr = $modelConfig->item('pay_alipay');
        if ($alipay_arr) $alipay_config = array_merge($alipay_config, $alipay_arr);

        $order_id = $this->get('order_id');
        if (empty($order_id)) die('订单号不能为空');

        $order = new ModelOrder();
        $order_info = $order->item($order_id);

        if (!$order_info) die('订单不存在');

        /**************************请求参数**************************/
        //支付类型
        $payment_type = "1";
        //必填，不能修改
        //服务器异步通知页面路径
        $notify_url = $this->pay_url."pay/alipay/notify";
        //需http://格式的完整路径，不能加?id=123这类自定义参数
        //页面跳转同步通知页面路径
        $return_url = $this->pay_url."pay/alipay/return";
        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/
        //商户订单号
        $out_trade_no = $order_id;
        //商户网站订单系统中唯一订单号，必填
        //订单名称
        $subject = $order_info['tostr'];
        //必填
        //付款金额
        $total_fee = sprintf('%.2f',$order_info['final_amount']);
        //必填
        //订单描述
        $body = '';
        //商品展示地址
        $show_url = '';
        //需以http://开头的完整路径，例如：http://www.商户网址.com/myorder.html
        //防钓鱼时间戳
        $anti_phishing_key = "";
        //若要使用请调用类文件submit中的query_timestamp函数
        //客户端的IP地址
        $exter_invoke_ip = "";
        //非局域网的外网IP地址，如：221.0.0.1

        //构造要请求的参数数组，无需改动
        $parameter = array(
            "service" => "create_direct_pay_by_user",
            "partner" => trim($alipay_config['partner']),
            "seller_email" => trim($alipay_config['seller_email']),
            "payment_type"	=> $payment_type,
            "notify_url"	=> $notify_url,
            "return_url"	=> $return_url,
            "out_trade_no"	=> $out_trade_no,
            "subject"	=> $subject,
            "total_fee"	=> $total_fee,
            "body"	=> $body,
            "show_url"	=> $show_url,
            "anti_phishing_key"	=> $anti_phishing_key,
            "exter_invoke_ip"	=> $exter_invoke_ip,
            "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
        );

        //建立请求
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
        $this->redirect($html_text);
        die;
    }

    /**
     * 服务器异步通知页面路径
     */
    public function actionNotify()
    {
        header("Content-type:text/html;charset=utf-8");

        $alipay_config = array();
        include(Yii::app()->basePath.'/extensions/alipay_direct/alipay.config.php');
        include(Yii::app()->basePath.'/extensions/alipay_direct/lib/alipay_notify.class.php');

        //计算得出通知验证结果
        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();

        if($verify_result) {//验证成功
            $out_trade_no = $_POST['out_trade_no'];
            //支付宝交易号
            $trade_no = $_POST['trade_no'];
            //交易状态
            $trade_status = $_POST['trade_status'];
            $buyer_email = isset($_GET['buyer_email'])?$_GET['buyer_email']:'';

            if($_POST['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
                $order = new ModelOrder();
                $order_info = $order->item($out_trade_no);
                if ($order_info['pay_status'] == 0)
                    $order->OrderPayment($out_trade_no,$buyer_email,$trade_no);
            }
            else {
                echo "支付状态失败".$_GET['trade_status'];
            }
            echo "success";		//请不要修改或删除
        }
        else {
            //验证失败
            echo "fail";
        }
    }

    /**
     * 跳转同步通知
     */
    public function actionReturn()
    {
        header("Content-type:text/html;charset=utf-8");

        $alipay_config = array();
        include(Yii::app()->basePath.'/extensions/alipay_direct/alipay.config.php');
        include(Yii::app()->basePath.'/extensions/alipay_direct/lib/alipay_notify.class.php');

        //计算得出通知验证结果
        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if($verify_result) {//验证成功
            //商户订单号
            $out_trade_no = $_GET['out_trade_no'];
            //支付宝交易号
            $trade_no = $_GET['trade_no'];
            //交易状态
            $trade_status = $_GET['trade_status'];
            $buyer_email = isset($_GET['buyer_email'])?$_GET['buyer_email']:'';

            if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
                $order = new ModelOrder();
                $order_info = $order->item($out_trade_no);
                if ($order_info['pay_status'] == 0)
                    $order->OrderPayment($out_trade_no,$buyer_email,$trade_no);
            }
            else {
                echo "支付状态失败".$_GET['trade_status'];
            }

            $this->redirect('/pay/default/success');
        }
        else {
            echo "验证失败";
        }
    }
}